/**
 * 
 */
package com.lemote.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

/**
 * @author wuhui
 * 
 *         下午04:02:44
 */
public class DataUtils {

	/**
	 * 备份数据库
	 * 
	 * @param username
	 *            数据库用户名
	 * @param password
	 *            数据库密码
	 * @param path
	 *            备份文件存放目录
	 * @param databaseName
	 *            数据库名
	 * @return
	 * @throws IOException
	 */
	public static boolean backup(String username, String password, String path,
			String databaseName) throws IOException {
		Runtime rt = Runtime.getRuntime();
		StringBuffer mysql = new StringBuffer("mysqldump -u").append(username)
				.append(" -p").append(password).append(" ")
				.append(databaseName);
		// 调用 mysql 的 cmd:
		Process child = rt.exec("cmd /c " + mysql);// 设置导出编码为utf8。这里必须是utf8
		// 把进程执行中的控制台输出信息写入.sql文件，即生成了备份文件。注：如果不对控制台信息进行读出，则会导致进程堵塞无法运行
		InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
		InputStreamReader read = new InputStreamReader(in, "utf8");// 设置输出流编码为utf8。这里必须是utf8，否则从流中读入的是乱码
		String inStr;
		StringBuffer sb = new StringBuffer();
		// 组合控制台输出信息字符串
		BufferedReader br = new BufferedReader(read);
		while ((inStr = br.readLine()) != null) {
			sb.append(inStr + "\r\n");
		}
		// 要用来做导入用的sql目标文件：
		FileOutputStream fout = new FileOutputStream(backDataBaseName(path,
				databaseName));
		OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
		writer.write(sb.toString());
		// 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
		writer.flush();
		// 别忘记关闭输入输出流
		in.close();
		read.close();
		br.close();
		writer.close();
		fout.close();
		System.out.println("/* Output OK! */");
		return true;
	}

	/**
	 * 恢复数据库(需要已有空数据库)
	 * 
	 * @param username数据库用户名
	 * @param password
	 *            数据库密码
	 * @param file
	 *            备份文件
	 * @param databaseName
	 *            数据库名
	 * @return
	 */
	public static boolean recove(String username, String password, File file,
			String databaseName) {// 还原
		try {
			Runtime rt = Runtime.getRuntime();
			// 调用 mysql 的 cmd:
			String mysql = new StringBuffer("mysql -u").append(username)
					.append(" -p").append(password).append(" ").append(
							databaseName).toString();
			Process child = rt.exec(mysql);
			OutputStream out = child.getOutputStream();// 控制台的输入信息作为输出流
			String inStr;
			StringBuffer sb = new StringBuffer("");
			String outStr;
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "utf8"));
			while ((inStr = br.readLine()) != null) {
				sb.append(inStr + "\r\n");
			}
			outStr = sb.toString();
			OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
			writer.write(outStr);
			// 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
			writer.flush();
			// 别忘记关闭输入输出流
			out.close();
			br.close();
			writer.close();
			System.out.println("/* Load OK! */");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public static String backDataBaseName(String path, String dbn) {
		StringBuffer bdbn = new StringBuffer(path);
		Calendar c = Calendar.getInstance();
		if (path != null && !path.endsWith("/")) {
			bdbn.append("/");
		}
		bdbn.append(c.get(c.YEAR)).append("/").append(c.get(c.MONTH) + 1)
				.append("/");
		File file = new File(bdbn.toString());
		if (!file.exists()) {
			file.mkdirs();
		}
		if (dbn != null) {
			bdbn.append(dbn).append("_bak_");
		} else {
			bdbn.append("bak_");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		String date = sdf.format(c.getTime());
		bdbn.append(date).append(".sql");
		return bdbn.toString();

	}

	/**
	 * 获取目录下所有文件名表
	 */
	public static List<File> fileList(File file) {
		return fileList(null, file, null);
	}

	/**
	 * 获取目录下所有指定格式文件名表
	 * 
	 * @param file
	 * @param suffix
	 *            后缀
	 */
	public static List<File> fileList(File file, String suffix) {
		return fileList(null, file, suffix);
	}

	private static List<File> fileList(List<File> files, File file,
			String suffix) {
		if (files == null) {
			files = new ArrayList<File>();
		}
		if (file == null || !file.exists()) {
			return files;
		}
		if (file.isDirectory()) {
			File[] fs = file.listFiles();
			for (File f : fs) {
				fileList(files, f, suffix);
			}
		} else {
			if (suffix == null || "".equals(StringUtils.trim(suffix))) {
				files.add(file);
			} else {
				if (file.getAbsolutePath().endsWith(suffix)) {
					files.add(file);
				}
			}
		}
		return files;
	}

	/**
	 * 读取指定key对象
	 */
	public static String getPropertiesValue(String key) {
		Properties prop = new Properties();
		InputStream in = null;
		try {
			in = DataUtils.class.getResourceAsStream("/system.properties");
			prop.load(in);
		if (in!=null) {
			in.close();
		}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return prop.getProperty(key);
	}

}
